<template>
  <div class="item-list">
    <div class="item-list-header">
      <div class="title">内容列表</div>
      <div class="actions">
        <t-dropdown :options="importOptions" @click="action.handleImportOption">
          <t-button theme="primary" size="small">
            <template #icon>
              <AddIcon />
            </template>
            导入内容
          </t-button>
        </t-dropdown>
        <div v-if="batchData.contentItems && batchData.contentItems.length > 0">
          <t-button
            variant="text"
            theme="danger"
            size="small"
            @click="action.clearAll"
          >
            清空
          </t-button>
        </div>
      </div>
    </div>

    <div class="item-list-content noscrollbar">
      <div v-if="!batchData.contentItems || batchData.contentItems.length === 0" class="empty-state">
        <div class="empty-text">暂无内容，请导入内容</div>
      </div>

      <div v-else class="item-list-items">
        <div
          v-for="item in batchData.contentItems"
          :key="item.id"
          class="item-card"
          :class="{ 'selected': selectedItemId === item.id }"
          @click="action.selectItem(item.id)"
        >
          <div class="item-type">
            <span class="type-badge" :class="item.type">{{ item.type === 'text' ? '文本' : '音频' }}</span>
          </div>
          <div class="item-content">
            <div class="item-name" :title="item.name || '未命名'">{{ item.name || '未命名' }}</div>
            <div class="item-preview">
              <div v-if="item.type === 'text'" class="text-preview">{{ item.text.substring(0, 50) + (item.text.length > 50 ? '...' : '') }}</div>
              <div v-else class="audio-preview">
                <div class="audio-duration">{{ item.duration || '未知时长' }}</div>
                <t-button class="preview-btn" size="small" @click.stop="action.previewAudio(item)">试听</t-button>
              </div>
            </div>
          </div>
          <div class="item-actions">
            <t-button variant="text" theme="danger" size="small" @click.stop="action.deleteItem(item.id)">
              <template #icon>
                <DeleteIcon />
              </template>
            </t-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 导入对话框组件 -->
    <BatchImportDialog
      v-model:visible="state.importDialogVisible"
      :importType="state.currentImportMethod"
      @import="action.handleImportResult"
      @cancel="state.importDialogVisible = false"
    />

    <!-- 确认删除对话框 -->
    <t-dialog
      v-model:visible="state.deleteConfirmVisible"
      header="确认删除"
      width="400px"
      :confirm-btn="{ content: '删除', theme: 'danger' }"
      :cancel-btn="{ content: '取消' }"
      @confirm="action.confirmDelete"
    >
      <p>
        {{ state.deleteConfirmMessage }}
      </p>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { AddIcon, ChevronDownIcon, DeleteIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { v4 as uuidv4 } from 'uuid';
import { Client } from '@renderer/client';
import { millisecondsToTime } from '@renderer/utils';
import BatchImportDialog from '@renderer/views/batch/items/BatchImportDialog.vue'

const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:modelValue', 'importItems', 'deleteItem', 'previewAudio']);

// 使用计算属性获取batchData，确保双向绑定
const batchData = defineModel({});

// 调试日志 - 检查数据变化
watch(() => batchData.value.contentItems, (newVal) => {
}, { deep: true });

const selectedItemId = ref(null);

const state = reactive({
  // 使用新的导入对话框
  importDialogVisible: false,
  currentImportMethod: 'text',
  uploading: false,

  // 删除相关
  deleteConfirmVisible: false,
  deleteConfirmMessage: '',
  itemToDelete: null,

  // 选择模式
  selectMode: false,
  selectedItems: []
});

const importOptions = [
  { content: '导入单篇文章', value: 'text' },
  { content: '导入单个音频', value: 'audio' },
  { content: '批量导入文章', value: 'excel' },
  { content: '批量导入音频', value: 'batchAudio' },
];

onMounted(() => {
});

const action = {
  handleImportOption({ value }) {
    state.currentImportMethod = value;

    switch (value) {
      case 'text':
      case 'excel':
      case 'batchAudio':
        // 使用新的对话框组件
        state.importDialogVisible = true;
        break;
      case 'audio':
        // 单个音频导入保持原有逻辑
        action.importAudio();
        break;
    }
  },

  // 处理导入结果
  handleImportResult(result) {

    if (result.type === 'text') {
      action.importItems(result.items);
    } else if (result.type === 'audio') {
      action.importItems(result.items);
    }

    state.importDialogVisible = false;
  },

  // 参照单任务代码改写导入音频功能
  async importAudio() {
    try {
      // 选择单个音频文件
      const filePath = await Client.file.selectAudio();
      if (!filePath) return;

      state.uploading = true;

      try {
        // 获取音频信息
        const info = await Client.file.getAudioInfo(filePath);

        // 验证音频
        if (action.checkAudio(info)) {
          const audioItem = {
            id: uuidv4(),
            type: 'audio',
            name: info.name || '未命名音频',
            audioUrl: filePath,
            duration: millisecondsToTime(info.duration * 1000),
            createdAt: new Date().toISOString(),
          };


          emit('importItems', [audioItem]);
          selectedItemId.value = audioItem.id;

          MessagePlugin.success('音频导入成功');
        }
      } catch (err) {
        console.error('解析音频信息失败', err);
        MessagePlugin.error('解析音频信息失败：' + (err.message || '未知错误'));
      } finally {
        state.uploading = false;
      }
    } catch (error) {
      console.error('导入音频文件失败', error);
      MessagePlugin.error('导入音频文件失败：' + (error.message || '未知错误'));
      state.uploading = false;
    }
  },

  // 验证音频信息，参照单任务代码
  checkAudio(audioInfo) {
    if (!audioInfo.isOK) {
      MessagePlugin.error(audioInfo.msg || '音频上传失败');
      return false;
    }
    if (audioInfo.duration > 60 * 30) {
      MessagePlugin.error('音频时长不能超过30分钟');
      return false;
    }
    return true;
  },

  // 导入项目到列表
  importItems(items) {
    // 同时触发事件
    emit('importItems', items);
  },

  selectItem(id) {
    selectedItemId.value = id;
  },

  deleteItem(id) {
    const item = batchData.value.contentItems.find(item => item.id === id);
    if (!item) return;

    state.itemToDelete = id;
    state.deleteConfirmMessage = `确定要删除"${item.name || '未命名'}"吗？`;
    state.deleteConfirmVisible = true;
  },

  // 切换选择项目
  toggleSelectItem(id) {
    if (state.selectedItems.includes(id)) {
      state.selectedItems = state.selectedItems.filter(itemId => itemId !== id);
    } else {
      state.selectedItems.push(id);
    }
  },

  // 清空所有项目
  clearAll() {
    if (!batchData.value.contentItems || batchData.value.contentItems.length === 0) return;

    state.deleteConfirmMessage = '确定要清空所有内容吗？';
    state.itemToDelete = null;
    state.deleteConfirmVisible = true;
  },

  // 确认删除
  confirmDelete() {
    if (state.itemToDelete) {
      // 单个删除
      const item = batchData.value.contentItems.find(item => item.id === state.itemToDelete);
      if (item && item.type === 'audio') {
        emit('previewAudio', { action: 'close', item });
      }

      // 创建新数组以确保Vue能检测到变化
      batchData.value = {
        ...batchData.value,
        contentItems: batchData.value.contentItems.filter(item => item.id !== state.itemToDelete),
        assignments: batchData.value.assignments.filter(assignment => assignment.contentId !== state.itemToDelete)
      };

      // 如果在选择列表中，也要移除
      if (state.selectedItems.includes(state.itemToDelete)) {
        state.selectedItems = state.selectedItems.filter(id => id !== state.itemToDelete);
      }

      // 更新选中项
      if (selectedItemId.value === state.itemToDelete) {
        selectedItemId.value = batchData.value.contentItems[0]?.id || null;
      }

      // 触发事件
      emit('deleteItem', state.itemToDelete);

      MessagePlugin.success('删除成功');
    } else if (state.selectedItems.length > 0) {
      // 批量删除
      // 关闭正在播放的音频
      const audioItems = batchData.value.contentItems
        .filter(item => state.selectedItems.includes(item.id) && item.type === 'audio');
      if (audioItems.length > 0) {
        emit('previewAudio', { action: 'close' });
      }

      // 创建新数组以确保Vue能检测到变化
      batchData.value = {
        ...batchData.value,
        contentItems: batchData.value.contentItems.filter(item => !state.selectedItems.includes(item.id)),
        assignments: batchData.value.assignments.filter(assignment => !state.selectedItems.includes(assignment.contentId))
      };

      // 更新选中项
      if (state.selectedItems.includes(selectedItemId.value)) {
        selectedItemId.value = batchData.value.contentItems[0]?.id || null;
      }

      // 触发事件
      state.selectedItems.forEach(id => {
        emit('deleteItem', id);
      });

      state.selectedItems = [];
      MessagePlugin.success('批量删除成功');
    } else {
      // 清空所有
      // 关闭正在播放的音频
      const audioItems = batchData.value.contentItems.filter(item => item.type === 'audio');
      if (audioItems.length > 0) {
        emit('previewAudio', { action: 'close' });
      }

      // 创建新数组以确保Vue能检测到变化
      batchData.value = {
        ...batchData.value,
        contentItems: [],
        assignments: []
      };

      selectedItemId.value = null;
      state.selectedItems = [];
      MessagePlugin.success('清空成功');
    }

    // 重置状态
    state.itemToDelete = null;
    state.deleteConfirmVisible = false;
  },

  previewAudio(item) {
    if (item.type === 'audio' && item.audioUrl) {
      emit('previewAudio', { action: 'play', item });
    }
  },
};

</script>

<style lang="less" scoped>
.item-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #ffffff;  // 由深色改为白色
  color: #333333;  // 文字由白色改为深色

  &-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e0e0e0;  // 边框由深色改为浅灰色

    .title {
      font-weight: 500;
      font-size: 16px;
      color: #333333;  // 文字由白色改为深色
    }

    .actions {
      display: flex;
      gap: 4px;
    }
  }

  &-content {
    flex: 1;
    overflow: auto;
    padding: 16px;
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;

    .empty-text {
      color: rgba(0, 0, 0, 0.6);  // 半透明白色改为半透明黑色
      font-size: 14px;
    }
  }

  .item-list-items {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .item-card {
    background: #fafafa;  // 深色背景改为浅灰白色
    border-radius: 4px;
    border: 1px solid #e0e0e0;  // 边框改为浅灰色
    transition: border-color 0.3s;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    cursor: pointer;

    &:hover {
      background-color: #f5f5f5;  // 添加悬停效果
    }

    &.selected {
      border-color: var(--td-brand-color);
      background-color: rgba(0, 82, 217, 0.05);  // 选中状态添加淡蓝色背景
    }

    &:last-of-type {
      margin-bottom: 21px;
    }

    .item-type {
      .type-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 2px;
        font-size: 12px;
        font-weight: 500;

        // 保持原有的徽章颜色，因为这些颜色已经很好看
        &.text {
          background: rgba(48, 156, 255, 0.1);
          color: #309CFF;
        }

        &.audio {
          background: rgba(255, 147, 47, 0.12);
          color: #FF932F;
        }
      }
    }

    .item-content {
      display: flex;
      flex-direction: column;
      gap: 4px;

      .item-name {
        font-weight: 500;
        font-size: 14px;
        color: #333333;  // 文字由白色改为深色
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .item-preview {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.6);  // 半透明白色改为半透明黑色

        .text-preview {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .audio-preview {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .preview-btn {
            min-width: 48px;
            height: 24px;
            border-radius: 2px;
            font-size: 12px;
          }
        }
      }
    }

    .item-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 4px;
    }
  }
}
</style>
